#!/bin/bash

json_file="../terraform/envs/$PROJECT_ENV/ecs/terraform.tfstate"
ansible_hosts='ansible_hosts'
ssh_key_file="../terraform/envs/$PROJECT_ENV/keypair/private_key-myapp-$PROJECT_ENV.pem"

# Empty ansible_hosts file
> $ansible_hosts

# read JSON file
output=$(jq -r '.outputs.ecs_info.value' $json_file)

# extract all group names
groups=$(echo "$output" | jq -r 'keys[]')

echo "###PROJECT_ENV: $PROJECT_ENV"
for group in $groups; do
    echo "[$group]" >> $ansible_hosts
    hosts=$(echo "$output" | jq -r --arg group "$group" '.[$group] | keys[]')
    for host in $hosts; do
        ip=$(echo "$output" | jq -r --arg group "$group" --arg host "$host" '.[$group][$host]')
        echo "$host ansible_host=$ip ansible_user=root ansible_ssh_private_key_file=$ssh_key_file" >> $ansible_hosts
    done
    echo "" >> $ansible_hosts  # Write a blank line for readability
done
